﻿using DocumentFormat.OpenXml.Lite.Helper;
using DocumentFormat.OpenXml.Lite.SpreadsheetML.Excel.Types;
using DocumentFormat.OpenXml.Lite.Xml;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;

namespace DocumentFormat.OpenXml.Lite.SpreadsheetML.Excel.RunProperties
{
    [XmlRoot("color", Namespace = Constants.ExcelMain)]
    public class Color : XmlSerializable, IRunProperty, IFontStyleElement
    {
        [Optional]
        [XmlAttribute("auto", Form = XmlSchemaForm.Qualified)]
        public Nullable<bool> Automatic { get; set; }

        [Optional]
        [XmlAttribute("indexed", Form = XmlSchemaForm.Qualified)]
        public Nullable<uint> Index { get; set; }

        /// <summary>
        /// Hexadecimal value. Length: 8.
        /// </summary>
        [Optional]
        [XmlAttribute("rgb", Form = XmlSchemaForm.Qualified)]
        public string RGB
        {
            get { return color; }
            set
            {
                if (value == null || value.Length != 8 ||
                    (value.Length == 8 && !Helpers.ParseHexadecimalValue(value)))
                {
                    throw new ArgumentException("String: " + value +
                        "is not a valid hexadecimal string or length is not 6!");
                }

                color = value;
            }
        }

        [Optional]
        [XmlAttribute("theme", Form = XmlSchemaForm.Qualified)]
        public Nullable<uint> Theme { get; set; }

        [Optional]
        [XmlAttribute("tint", Form = XmlSchemaForm.Qualified)]
        public Nullable<double> Tint { get; set; }

        [XmlIgnore]
        private string color;

        public Color() { }

        public void Copy(object obj)
        {
            if (obj is Color)
            {
                this.RGB = (obj as Color).RGB;
                this.Tint = (obj as Color).Tint;
                this.Theme = (obj as Color).Theme;
                this.Index = (obj as Color).Index;
                this.Automatic = (obj as Color).Automatic;
            }
        }
    }
}
